<script lang="ts">
	import { page } from '$app/stores';
	import Divider from '$components/basic/divider/divider.svelte';
	// import Carousel from './_com/carousel.svelte';
	import { Image } from '@smui/image-list';
	import Carousel from 'svelte-carousel';
	import Detail from './_com/detail.svelte';
	import alova, { abort_req } from '$utils/request';
	import PageLoading from '$components/basic/loading/PageLoading.svelte';
	import { useNavBarStore } from '@/store/modules/navBar';
	import { getValue } from '$utils/get';
	import ProductTip from '$components/business/product-tip';
	import Recomemd from './_com/recomemd.svelte';
	import Picture from '$components/basic/picture/picture.svelte';
	import { ITEM_TYPE_ENUM } from '$components/business/product';
	import { useInClient } from '@/hooks/inClient';

	let carousel;
	let sideBar = [];
	let loading = true;
	let error: number | string = '';
	let detail: Partial<Product.Detail> = {};
	let markText = 'unknown';
	const { signal } = abort_req();

	const errCallback = (err: string | number = '') => {
		loading = false;
		error = err;
	};

	let recommendLoading = true;
	let recommendData: { title: string; items: IObject[] }[] = [];
	const getRecommendList = (id) => {
		recommendLoading = true;
		const instance = alova.Get(`/product/detail-item?itemId=${id}&ip`);
		instance.then((res) => {
			recommendLoading = false;
			if ((res as any).data) recommendData = Object.values((res as any).data);
		});
		instance.catch(() => (recommendLoading = false));
	};

	const getProductDetail = async (id: number | string) => {
		loading = true;
		alova
			.Post('/product/detail', { id: Number(id) }, { signal })
			.then((res) => {
				const { code, data } = res as any;
				if (code === 500 || code === 404) return errCallback(code);
				if (code === 504) return errCallback(code);
				if (!data) return errCallback();
				const { category_tree, detail: dtl, prev, next } = (res as any).data;

				loading = false;
				sideBar = category_tree;
				detail = dtl as Product.Detail;
				detail.num = dtl.moq;
				markText = detail.itemType!;

				useNavBarStore().setPrevAndNext(getValue(prev, 'id', ''), getValue(next, 'id', ''));
			})
			.catch(() => (loading = false));

		getRecommendList(id);
	};

	const initData = () => {
		const reg = new RegExp(/\/detail\/(\d+)/);
		const detailId = $page.url.pathname.match(reg)?.[1];

		if (detailId) getProductDetail(detailId);
	};

	let current = '';

	const { inClient } = useInClient();

	$: {
		if ($page.url.pathname !== current && $inClient) {
			current = $page.url.pathname;
			initData();
		}
	}

	$: description = detail.content || 'detail';
	$: imageList = [{ url: detail.thumb, name: 'thumb' }, ...(detail.pics || [])];

	const carry_info =
		'Products of the "CloseOut" type have a high MOQ (Minimum Order Quantity), meaning that everyone needs to combine their orders. The order will only be confirmed once the progress bar reaches 100%. If not, the order will be canceled and not successful.';
</script>

<svelte:head>
	<title>{detail.title ?? ''}</title>
</svelte:head>

<div class="w-full flex-cc flex-col h-full">
	<div class="w-1320px h-full max-w-100% min-w-1320px flex flex-row">
		<!-- <Side list={sideBar} series={detail.series} category={detail.level2_category} /> -->
		<!-- <Aside list={$list} bind:checkedLists on:action={listenChecked} /> -->
		<main class="flex-1 h-full px-20px flex flex-col relative overflow-hidden gap-20px pt-20px">
			<PageLoading {loading} err_status={error}>
				<!-- <Marker text={markText} /> -->
				<div class="w-full h-fit relative flex flex-row justify-start items-start">
					<ProductTip
						content={detail.itemType}
						date={detail.date}
						class="after:border-color-transparent!"
					/>
					<!-- <Carousel images={imageList} style="--item-width: 600px; --item-height: 500px;" /> -->
					<div class="w-600px">
						<Carousel
							bind:this={carousel}
							arrows={false}
							autoplay={imageList.length ? true : false}
						>
							{#each imageList as image}
								<div class="w-full flex-cc">
									<Picture class="w-500px h-500px" src={image.url} alt={image.name} />
								</div>
							{/each}

							<!-- <div>2</div>
							<div>3</div> -->
						</Carousel>
					</div>
					<Detail bind:orderInfo={detail} style="height: 500px;" />
				</div>
				<Divider style="--mdc-theme-primary: #d1d5db" />

				{#if detail.itemType === ITEM_TYPE_ENUM.CLOSE_OUT}
					<div class="color-red-4 p-10px bg-red-1 font-size-14px">
						<div class="title font-size-24px font-500">CARRY:</div>
						<p class="p-0 pl-20px m-0">{carry_info}</p>
					</div>
				{/if}
				<div class="title font-size-24px font-500">Content:</div>
				<div class="w-full mb-20px">{@html description}</div>
				<!-- <Divider style="--mdc-theme-primary: #d1d5db" /> -->
			</PageLoading>
		</main>
	</div>
	{#if !recommendLoading}
		<div class="w-1448px max-w-100% min-w-1320px gap-20px">
			<Recomemd bind:data={recommendData} />
		</div>
	{/if}
</div>
